/*
 * This file is part of BestApp.

    BestApp is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BestApp is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with BestApp.  If not, see <http://www.gnu.org/licenses/>.

 */

package org.enate.BESTApp;

import java.util.ArrayList;
import java.util.List;

import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;


public class DataProvider extends ContentProvider {
		
	//-------------------------------------------------------------------------------------------------------
	// ~~~ Variables ~~~
	private static final boolean LOLCAT = false;
	private static final String TAG = "DataProvider";
	public static final String AUTHORITY = "org.enate.BESTApp.provider";
	public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
	public static final Uri CONTENT_URI_MESSAGES = CONTENT_URI.buildUpon().appendEncodedPath("data").build();
	private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
	private static final int URI_DATA = 0;
	static {URI_MATCHER.addURI(AUTHORITY, "data/*", URI_DATA);}
	private static Context ctx = null;
	protected static Resources res;
	public static List<int[]> result;
	protected static int getAllWidgetIds_iterator = 0;	
	static Object[] values;

	static int CurPersonID = 0;
	
	// Contact sub query cache:
	protected static Object[] ContactLookup = new Object[3];
	protected static ArrayList<Integer> AL_cached_ContactDetails_DISPLAY_NAMEID = new ArrayList<Integer>();
	protected static ArrayList<String>  AL_cached_ContactDetails_DISPLAY_NAME = new ArrayList<String>();
	protected static ArrayList<String> AL_cached_ContactDetails_CONTACT_ID = new ArrayList<String>();
	protected static int INT_CACHE_INDEX =0;

	protected static int INT_CUR_PERSON_COLUMNINDEX = 0;
	protected static int INT_MESSAGE_TYPE = 0;


	//-------------------------------------------------------------------------------------------------------
	@Override 
	public boolean onCreate() {
		if(null==ctx) {ctx = getContext();}
		registerSMSObserver();
		res = ctx.getResources();
		return false;
	}
	
	//-------------------------------------------------------------------------------------------------------
	public static int[] getAllWidgetIds(Context context) {
    	AppWidgetManager awm = AppWidgetManager.getInstance(context);
    	result = new ArrayList<int[]>();
    	result.add(awm.getAppWidgetIds(new ComponentName(context, AppWidget4x4.class)));
    	getAllWidgetIds_iterator = 0;
    	for(int[] arr:result) getAllWidgetIds_iterator += arr.length;
    	int[] res = new int[getAllWidgetIds_iterator];
    	getAllWidgetIds_iterator = 0;
    	for(int[] arr:result){for(int id:arr){res[getAllWidgetIds_iterator++]=id;}}
    	return res;
    }
    
	//-------------------------------------------------------------------------------------------------------
	@Override public int delete(Uri uri, String selection, String[] selectionArgs) {return 0;}
	@Override public String getType(Uri uri) {return null;}
	@Override public Uri insert(Uri uri, ContentValues values) {return null;}
	@Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {return 0;}
	public static void notifyDatabaseModification(int widgetId) {ctx.getContentResolver().notifyChange(CONTENT_URI_MESSAGES.buildUpon().appendEncodedPath(Integer.toString(widgetId)).build(), null);}

	//-------------------------------------------------------------------------------------------------------
	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		if(URI_MATCHER.match(uri)==URI_DATA) {
			 return cursor_loadConversations();
		}return null;
	}
    
    //-------------------------------------------------------------------------------------------------------
    // Conversations View:
    public static ExtMatrixCursor cursor_loadConversations() {
    	ExtMatrixCursor ret = new ExtMatrixCursor(API.PROJECTION_APPWIDGETS_CONVERSATIONLIST);
    	values = new Object[API.PROJECTION_APPWIDGETS_CONVERSATIONLIST.length];
    	final Cursor cur = cr.query(API.CONTENT_URI_MMS_SMS_CONVERSATIONS, null,null, null,"date DESC");
    	try {
    		if(null!=cur&&cur.getCount()>0&&cur.moveToFirst()){
    			do{
    				try {
    					ContactLookup = API.getContactNameorNumber(cr, ContactLookup, cur.getLong(cur.getColumnIndex("recipient_ids")));
    					values[API.DataProviderColumns_CONVERSATIONLIST._id.ordinal()] = cur.getString(cur.getColumnIndex("_id"));
    					values[API.DataProviderColumns_CONVERSATIONLIST.date.ordinal()] = API.formatTimestamp(cr,cur.getLong(cur.getColumnIndex("date")));
    					values[API.DataProviderColumns_CONVERSATIONLIST.message_count.ordinal()] = cur.getString(cur.getColumnIndex("message_count"));
    					values[API.DataProviderColumns_CONVERSATIONLIST.recipient_ids.ordinal()] = cur.getString(cur.getColumnIndex("recipient_ids"));
    					values[API.DataProviderColumns_CONVERSATIONLIST.snippet.ordinal()] = cur.getString(cur.getColumnIndex("snippet"));
    					values[API.DataProviderColumns_CONVERSATIONLIST.read.ordinal()] = cur.getString(cur.getColumnIndex("read"));
    					values[API.DataProviderColumns_CONVERSATIONLIST.error.ordinal()] = cur.getString(cur.getColumnIndex("error"));
    					values[API.DataProviderColumns_CONVERSATIONLIST.has_attachment.ordinal()] = cur.getString(cur.getColumnIndex("has_attachment"));
    					values[API.DataProviderColumns_CONVERSATIONLIST.contact_name.ordinal()] = ContactLookup[1].toString().equals("NAN")?"Unknown Name":ContactLookup[1].toString();
    					values[API.DataProviderColumns_CONVERSATIONLIST.contact_photo.ordinal()] = Long.parseLong(ContactLookup[0].toString()) > 0 ? API.loadContactPhoto(cr, Long.parseLong(ContactLookup[0].toString())) : null;
    					values[API.DataProviderColumns_CONVERSATIONLIST.contact_id.ordinal()] = ContactLookup[0].toString();
    					values[API.DataProviderColumns_CONVERSATIONLIST.lookup_id.ordinal()] = ContactLookup[2].toString();
    					
    					
    					
    					
    					
    					
    					
    					ret.addRow(values);
    				}catch(Exception e) {e.printStackTrace();}
	    			
	    		}while(cur.moveToNext());
    		}
    	}catch(Exception e){if(LOLCAT)Log.e(TAG, e.toString(), e);}
    	finally{if(cur!=null && !cur.isClosed()){cur.close();}}
        return ret;
    }
	

    
//-------------------------------------------------------------------------------------------------------
// SMS ContentObserver class
   
    //-------------------------------------------------------------------------------------------------------
    public static Uri uriSMS;
    public static ContentResolver cr;
    public static SMSObserver observerSMS;
    public static Handler handler;
	protected static int int_cursor_getCount = 0;
	
	//-------------------------------------------------------------------------------------------------------
    private void registerSMSObserver(){
    	observerSMS = new SMSObserver(handler);
    	uriSMS = Uri.parse("content://mms-sms/conversations/");
		cr = ctx.getContentResolver();
		cr.registerContentObserver(uriSMS, false, observerSMS);
		cr.notifyChange(uriSMS, observerSMS);
	}
    
    //-------------------------------------------------------------------------------------------------------
	protected static void unregisterSMSObserver(){
		cr.unregisterContentObserver(observerSMS);
	}

	//-------------------------------------------------------------------------------------------------------
    class SMSObserver extends ContentObserver {public SMSObserver(Handler h) {super(h);}
        public void onChange(boolean selfChange) {
    		Cursor	c = ctx.getContentResolver().query(uriSMS,null,"read=0",null,null);
    		if (API.getUnreadSmsCount(ctx, 0)!=c.getCount()) {
    			int_cursor_getCount = c.getCount();
    			c.close();
    			//if(int_cursor_getCount>0){}
    		}
    		API.processWidgetUpdate(ctx);
        }
    }   
}